<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/12/18
 */

namespace app\models\live;

use app\Redis;
use wanyue\basic\BaseModel;
use app\models\user\User;
use app\models\user\UserAttent;
use app\models\live\LiveRecord;

/**
 * TODO 直播Model
 * Class StoreCart
 * @package app\models\store
 */
class Live extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'uid';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'live';

    protected static $def_field = 'uid,title,thumb,classid,province,city,showid,goodsnum,nums,likes,isvideo,pull';

    protected static $redis_userlist = 'user_';
    protected static $redis_enter = 'live_enter_';

    public static function getList($page = 0, $limit = 0, $expire = 3)
    {
        if (!$limit) return [];

        $key='live_list_'.$page.'_'.$limit;
        $list=Redis::get($key);
        if (!$list) {
            $model = self::where('islive',1)->order('starttime desc')->field(self::$def_field);
            if ($page) $model->page($page, $limit);
            $list = $model->select()->toArray();
            if($list){
                foreach ($list as &$item){
                    $item=self::handelInfo($item);
                }
                Redis::set($key, $list, $expire);
            }else{
                Redis::del($key);
            }
        }
        return $list;
    }

    //分类下直播
    public static function getClassList($classid, $page = 0, $limit = 0, $expire= 3)
    {
        if (!$limit) return [];
        $key='live_list_'.$classid.'_'.$page.'_'.$limit;
        $list=Redis::get($key);
        if (!$list) {
            $model = self::where('classid',$classid)->where('islive',1)->order('starttime desc')->field(self::$def_field);
            if ($page) $model->page($page, $limit);
            $list = $model->select()->toArray();
            if($list){
                foreach ($list as &$item){
                    $item=self::handelInfo($item);
                }
                Redis::set($key, $list, $expire);
            }else{
                Redis::del($key);
            }
        }
        return $list;
    }

    //关注直播
    public static function getFollowList($uid, $page = 0, $limit = 0, $expire= 3)
    {
        if (!$limit) return [];
        $key='live_list_'.$uid.'_'.$page.'_'.$limit;
        $list=Redis::get($key);
        if (!$list) {
            $followuids=UserAttent::getFollowIds($uid);
            if(!$followuids){
                Redis::del($key);
                return [];
            }

            $model = self::where('uid','in',$followuids)->where('islive',1)->order('starttime desc')->field(self::$def_field);
            if ($page) $model->page($page, $limit);
            $list = $model->select()->toArray();
            if($list){
                foreach ($list as &$item){
                    $item=self::handelInfo($item);
                }
                Redis::set($key, $list, $expire);
            }else{
                Redis::del($key);
            }
        }
        return $list;
    }

    //搜索直播
    public static function search($keyword, $page = 0, $limit = 0, $expire= 3)
    {

        $key='live_list_'.$keyword.'_'.$page.'_'.$limit;
        $list=Redis::get($key);
        if (!$list) {
            $model = self::alias('l');
            $model = $model->join('user u','u.uid=l.uid');
            $model = $model->where('u.nickname|l.title','like','%'.$keyword.'%')->where('l.islive',1)->order('l.starttime desc')->field('l.uid,l.title,l.thumb,l.classid,l.province,l.city,l.showid,l.goodsnum,l.nums,l.likes,l.isvideo,l.pull');
            if ($page) $model->page($page, $limit);
            $list = $model->select()->toArray();
            if($list){
                foreach ($list as &$item){
                    $item=self::handelInfo($item);
                }
                Redis::set($key, $list, $expire);
            }else{
                Redis::del($key);
            }
        }
        return $list;
    }

    public static function handelInfo($info )
    {

        $info['likes']=NumberFormat($info['likes']);
        
        $stream=$info['uid'].'_'.$info['showid'];
        $info['nums']=NumberFormat(Redis::zCard('user_'.$stream));
        $info['stream']=$stream;
        if(!$info['isvideo']){
            $info['pull']=self::getStreamUrl($stream);
        }

        $nickname='';
        $avatar='';
        $userinfo=User::getUserInfo($info['uid'],'nickname,avatar');
        if($userinfo){
            $nickname=$userinfo['nickname'];
            $avatar=$userinfo['avatar'];
        }
        $info['nickname']=$nickname;
        $info['avatar']=$avatar;

        if($info['thumb']=='') $info['thumb']=$avatar;

        $goods_img='';
        $info['goods_img']=$goods_img;

        return $info;
    }

    //获取直播信息
    public static function getInfo($where )
    {
        return self::where($where)->find();
    }

    //是否直播
    public static function islive($uid )
    {
        return self::where('uid',$uid)->where('islive',1)->field('showid')->find();
    }

    //小程序开播
    public static function setLiveByRoutine($uid,$stream,$title,$classid,$thumb='',$province='',$city='',$deviceinfo='')
    {

        $userinfo=User::getUserInfo($uid,'uid,nickname,avatar,isshop');
        if(!$userinfo || $userinfo['isshop']!=1) return self::setErrorInfo('无开播权限');
        if($classid>0){
            if(!LiveClass::getInfo($classid)) return self::setErrorInfo('分类不存在');
        }

        $islive=0;
        $starttime=time();

        $stream_a=explode('_',$stream);
        $showid = isset($stream_a[1])? $stream_a[1] : '0';

        $source=3;

        $goodsnum=0;

        $info=self::where('uid',$uid)->find();
        if($info){
            $info->title=$title;
            $info->classid=$classid;
            $info->thumb=$thumb;
            $info->province=$province;
            $info->city=$city;
            $info->deviceinfo=$deviceinfo;
            $info->islive=$islive;
            $info->showid=$showid;
            $info->starttime=$starttime;
            $info->goodsnum=$goodsnum;
            $info->source=$source;
            $info->likes=0;
            $info->goods=0;
            $info->nums=0;
            $info->isvideo=0;
            $info->pull='';
            $res=$info->save();
        }else{
            $res= self::create(compact('uid','title','classid','thumb','province','city','deviceinfo','islive','showid','starttime','goodsnum','source'));
        }

        if(!$res) return self::setErrorInfo('开播失败');

        $chatserver = sys_config('chatserver');
        $push=self::getStreamUrl($stream,'1');

        $token=md5(md5($uid));
        $userinfo['sign']=0;
		$userinfo['stream']=$stream;
        $userinfo['usertype']=50;
        Redis::set($token,$userinfo);

        return compact('stream','push','chatserver','token');

    }

    //开播
    public static function setLive($uid,$title,$classid,$thumb='',$province='',$city='',$deviceinfo='',$source='0')
    {

        $userinfo=User::getUserInfo($uid,'isshop,avatar');
        if(!$userinfo || $userinfo['isshop']!=1) return self::setErrorInfo('无开播权限');
        if($classid>0){
            if(!LiveClass::getInfo($classid)) return self::setErrorInfo('分类不存在');
        }
        if($thumb=='') $thumb=$userinfo['avatar'];

        $islive=0;
        $showid=time();
        $starttime=time();

        $goodsnum=0;

        $info=self::where('uid',$uid)->find();
        if($info){
            $info->title=$title;
            $info->classid=$classid;
            $info->thumb=$thumb;
            $info->province=$province;
            $info->city=$city;
            $info->deviceinfo=$deviceinfo;
            $info->islive=$islive;
            $info->showid=$showid;
            $info->starttime=$starttime;
            $info->goodsnum=$goodsnum;
            $info->source=$source;
            $info->likes=0;
            $info->goods=0;
            $info->nums=0;
            $info->isvideo=0;
            $info->pull='';
            $res=$info->save();
        }else{
            $res= self::create(compact('uid','title','classid','thumb','province','city','deviceinfo','islive','showid','starttime','goodsnum','source'));
        }

        if(!$res) return self::setErrorInfo('开播失败');

        $chatserver = sys_config('chatserver');
        $stream=$uid.'_'.$showid;
        $push=self::getStreamUrl($stream,'1');

        $token=md5(md5($uid));
        $userinfo=User::getUserInfo($uid,'uid,nickname,avatar');
        $userinfo['sign']=0;
        $userinfo['stream']=$stream;
        $userinfo['usertype']=50;
        Redis::set($token,$userinfo);

        return compact('stream','push','chatserver','token');

    }

    //关播
    public static function stopLive($uid,$showid)
    {

        if(!$uid || !$showid) return false;

        $info=self::where('uid',$uid)->where('showid',$showid)->find();
        if($info) $info=$info->toArray();

        self::where('uid',$uid)->where('showid',$showid)->delete();
        if(!$info || $info['islive']!=1) return self::setErrorInfo('信息错误');

        $res= LiveRecord::setRecord($info);
        if(!$res) return self::setErrorInfo('关播失败');

        //清楚redis
        $key1=self::$redis_userlist.$uid.'_'.$showid; //用户列表
        $key2=self::$redis_enter.$uid.'_'.$showid; //进房间记录
        $key=$key1.','.$key2;
        Redis::del($key);

        return true;

    }

    //点赞
    public static function setLikes($uid,$showid,$likes=1)
    {

        if(!$uid || !$showid) return false;

        $info=self::where('uid',$uid)->where('showid',$showid)->inc('likes',$likes)->update();

        if(!$info ) return self::setErrorInfo('操作失败');

        return true;

    }

    //商品数添加
    public static function incGoodsnum($uid,$nums=1)
    {
        $info=self::where('uid',$uid)->inc('goodsnum',$nums)->update();
        return true;
    }

    //商品数减少
    public static function decGoodsnum($uid,$nums=1)
    {
        $info=self::where('uid',$uid)->where('goodsnum','>=',$nums)->dec('goodsnum',$nums)->update();
        return true;
    }

    //销售商品数添加
    public static function incGoods($uid,$nums=1)
    {
        $info=self::where('uid',$uid)->inc('goods',$nums)->update();
        return true;
    }

    //更新直播状态
    public static function upIslive($uid,$islive=1)
    {
        return self::where('uid',$uid)->update(['islive'=>$islive]);
    }

    //直播间在线人数
    public static function getNums($stream)
    {
        $key=self::$redis_userlist.$stream;

        $nums=Redis::zCard($key);

        $nums=NumberFormat($nums);

        return $nums;
    }

    //累计处理
    public static function setNums($uid,$liveuid,$showid)
    {
        $key=self::$redis_enter.$liveuid.'_'.$showid;
        $isexist=Redis::hGet($key,$uid);
        if(!$isexist){
            Redis::hSet($key,$uid,'1');
            self::incNums($liveuid,1);
        }
        return true;
    }
    //增加累计人数
    public static function incNums($uid,$nums=1)
    {
        return self::where('uid',$uid)->inc('nums',$nums)->update();
    }

    //获取推拉流地址
    /**
     * 获取推拉流地址
     * @param $stream 流名（可以带后缀格式）
     * @param $host 协议
     * @param $type 类型 0播流 1推流 2推流信息数组
     * @return string|array  地址信息
     */
    public static function getStreamUrl($stream,$type='0',$host='http')
    {
        $bizid = sys_config('tx_bizid');
        $push_url_key = sys_config('tx_push_key');
        $push = sys_config('tx_push');
        $pull = sys_config('tx_pull');

        $stream_a=explode('.',$stream);
        $streamKey = isset($stream_a[0])? $stream_a[0] : '';
        $ext = isset($stream_a[1])? $stream_a[1] : '';

        //$live_code = $bizid . "_" .$streamKey;
        $live_code = $streamKey;

        $now_time = time() + 3*60*60;
        $txTime = dechex($now_time);

        $txSecret = md5($push_url_key . $live_code . $txTime);
        $safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;

        if($type==2){
            $url=array(
                'cdn'=>"rtmp://{$push}/live",
                'stream'=>$live_code.$safe_url,
            );

        }else if($type==1){
            //$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" .  $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url;	可录像
            //$url = "rtmp://" . $bizid .".livepush2.myqcloud.com/live/" . $live_code . "?bizid=" . $bizid . "" .$safe_url;
            $url="rtmp://{$push}/live/".$live_code.$safe_url;
        }else{
            if($host=='rtmp'){
                $url = "rtmp://{$pull}/live/" . $live_code ;
            }else{
                $host='https';
                $site_url = sys_config('site_url');
                if(strstr($site_url,'https')){
                    //$host='https';
                }
                $default_ext='flv';
                if($ext){
                    $default_ext = $ext;
                }
                $url = "{$host}://{$pull}/live/" . $live_code . ".".$default_ext;

            }
        }
        return $url;
    }
}